<template>
  <!-- 用户信息 -->
  <div class="userinfo jsb">
    <div class="hasspread" @click="handleClick">
      <i
        :class="`iconfont ${
          isCollapse ? 'icon-caidanzhankai' : 'icon-caidanshouqi'
        }`"
      ></i>
    </div>
    <div class="info aic">
      <div class="location">
        <el-popover placement="bottom" :width="200" trigger="hover">
          <template #reference>
            <el-icon color="#000" size="24"><location-information /></el-icon>
          </template>
          <div>
            当前位置: <span style="font-size: 12px">{{ currentArea }}</span>
          </div>
          <div>
            当前时间: <span style="font-size: 12px">{{ currentTime }}</span>
          </div>
          <div>
            登录时间:
            <span style="font-size: 12px">{{ $store.state.loginTime }}</span>
          </div>
        </el-popover>
      </div>
      <div class="avatar aic">
        <el-popover placement="bottom" :width="200" trigger="hover">
          <template #reference>
            <img :src="$store.state.userinfo.avatar" alt="" v-if="avatarImg" />
            <el-icon color="#333" size="24" v-else><avatar /></el-icon>
          </template>
          <div @click="editUser">修改信息</div>
          <div>附近公交站点: <span>{{ busStation }}</span></div>
          <!-- <div>附近地铁站点: {{ busStation }}</div> -->
        </el-popover>
        <span>{{ $store.state.userinfo.nick_name || nickname }}</span>
      </div>
      <div class="switchButton aic" @click="logout">
        <el-icon color="#333" size="24"><switch-button /></el-icon> 退出登录
      </div>
    </div>
  </div>
  <!-- 面包屑 -->
  <div class="bread_bar aic">
    <div class="crumbs aic">
      <span>您当前的位置:</span>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="item in routeData"
          :key="item.path"
          :to="{ path: item.path }"
        >
          <i :class="`iconfont ${item.icon}`"></i>
          {{ item.title }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
  </div>
  <!-- 地图 -->
  <div id="mysubway" v-show="false"></div>
</template>

<script setup>
import { LocationInformation, Avatar, SwitchButton } from "@element-plus/icons";
import { ref, watch, reactive, onMounted, onBeforeUnmount } from "vue";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
import { getCurrentTime } from "@/utils/Time/index.js";

const store = useStore();
const route = useRoute();
const router = useRouter();
const isCollapse = ref(false);
let routeData = ref([]);
let avatarImg = ref("");
const nickname = ref("请填写昵称");
let currentArea = ref("定位中...");
let timer = ref(null); // 时间函数
let currentTime = ref(""); // 当前时间
let systemGreet = ref(""); // 系统的问候
const longitude = ref(""); // 经度
const latitude = ref(""); // 纬度
const cityCode = ref(""); // 城市编号
const busStation = ref(""); // 公交车站点
const Amap = ref(""); // 整体地图
timer.value = setInterval(() => {
  currentTime.value = getCurrentTime();
});
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});

// 点击是否展开列表
const handleClick = () => {
  isCollapse.value = store.state.isCollapse;
  store.commit("changeCollapse", !isCollapse.value);
};
// 获取路由路径
const getRouterPath = () => {
  let matched = route.matched.filter(
    (item) => item && item.meta && item.meta.title
  );

  let first = matched[0];

  let temp = matched.map((item) => {
    if (item.path != "/home") {
      return {
        path: item.path,
        title: item.meta.title,
        icon: item.meta.icon,
      };
    } else {
      return {};
    }
  });

  routeData.value = [{ path: "/home", title: "首页", icon: "" }, ...temp];
};

// 高德地图
// // 获取当前的位置
const getPosition = () => {
  Amap.value = new AMap.Map("container", {
    resizeEnable: true,
    center: [latitude.value, longitude.value],
  });
  Amap.value.plugin("AMap.Geolocation", () => {
    let geolocation = new AMap.Geolocation({
      // 是否使用高德精准定位,默认true
      enableHighAccuracy: true,
      // 设置定位超时时间,
      timeout: 500,
      extensions: "all", // 是否需要详细的你地理编码信息，默认'base'
      needAddress: true, // 是否需要将定位结果进行逆地理编码操作
    });
    Amap.value.addControl(geolocation);
    geolocation.getCurrentPosition();
    AMap.event.addListener(geolocation, "complete", onComplete);
    AMap.event.addListener(geolocation, "err", onError);
  });
};

// 定位成功
const onComplete = (data) => {
  let { addressComponent, position } = data;
  cityCode.value = addressComponent.citycode;
  let province = addressComponent.province; // 省份
  let city = addressComponent.city; // 城市
  let district = addressComponent.district; //地区
  latitude.value = position.lat; // 纬度
  longitude.value = position.lng; // 经度
  currentArea.value = province + city + district;
  // 获取公交车站点
  Amap.value.plugin(["AMap.PlaceSearch"], () => {
    let linesearch = new AMap.PlaceSearch({
      pageIndex: 1, //页码，默认值为1
      pageSize: 1, //单页显示结果条数，默认值为20，最大值为50
      city: cityCode.value, //限定查询城市，可以是城市名（中文/中文全拼）、城市编码，默认值为『全国』
      extensions: "all", //是否返回公交线路详细信息，默认值为『base』
    });
    linesearch.searchNearBy(
      "公交站点",
      [longitude.value, latitude.value],
      1500,
      (status, result) => {
        if ((result.info == "OK", status == "complete")) {
          let { poiList } = result;
          busStation.value = poiList.pois[0].name;
        }
      }
    );
  });
  // 获取地铁站点
 
};

// 定位错误
const onError = () => {
  currentArea.value = "定位失败";
  getPosition();
};
// 编辑用户资料
const editUser = () => {
  router.push("/information");
};

// 页面一加载就获取当前的位置
onMounted(() => {
  // 获取当前的定位
  getPosition();
  // Tamp()
  // 获取用户信息
  avatarImg.value = store.state.userinfo.avatar;
});
// 监听路由
watch(
  () => route,
  (val) => {
    getRouterPath();
  },
  { immediate: true, deep: true }
);
// 监听store
// watch(
//   () => store.state.userinfo,
//   (val) => {
//     console.log(val);
//   },{deep:true,immediate:true}
// );

// 退出登录
const logout = () => {
  router.replace("/login");
  store.commit("setToken", "");
  store.commit("setUserInfo", {});
};
</script>

<style lang="scss">
.el-popover.el-popper.is-light {
  div {
    height: 30px;
    line-height: 30px;
    border-bottom: 1px solid #ddd;
    font-size: 12px;
    cursor: pointer;
    span{
      color:#0088c7;
    }
  }
}

@import url("../../globalStyle/flex.css");
@import url("../../globalStyle/color.scss");

.bread_bar {
  @include h(30px);
  padding: 10px 0;
  margin-bottom: 10px;
  @include bdd(1px, #ccc);
  @include bg(#fff);
  span {
    @include c(#000);
    @include fs();
    margin-right: 10px;
  }
  .crumbs {
    @include c(#fff);
    margin-left: 20px;
    .el-breadcrumb {
      font-size: 14px;
    }
    .el-breadcrumb__item {
      .el-breadcrumb__inner {
        @include c(#333);
        &.is-link {
          @include c(#000);
        }
      }
    }
  }
}
.hasspread {
  i {
    @include c();
    @include fs(26px);
  }
}
.userinfo {
  @include h(50px);
  @include c(#000);
  @include bg(#fff);

  margin-bottom: 10px;
  padding: 0 20px;
  .avatar {
    @include c(#666);
    @include fs(14px);
    cursor: pointer;

    span {
      margin-left: 10px;
    }

    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }
  }
  .location,
  .switchButton {
    margin: 0 30px;
    @include fs(12px);
  }
  .location >>> .tipTile {
    @include fs(12px);
  }
}
.titleStyle {
  font-size: 12px;
}
</style>
